package sw6.visualschedule.persistence;

import com.j256.ormlite.stmt.PreparedQuery;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.stmt.SelectArg;

import sw6.visualschedule.entities.ScheduleActivity;
import sw6.visualschedule.entities.Step;

import android.content.Context;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class StepRepo extends AbstractDataRepo<Step> {

    private static final String LOG_NAME = "StepService";
    
    /**
     * Initializes the repository.
     * @param base the context to run in.
     */
    public StepRepo(final Context base) {
        super(Step.class);
        
        this.attachBaseContext(base);
    }
    
    /**
     * Returns an ordered list of steps for an activity.
     * @param act the activity.
     * @return an ordered list of steps.
     */
    public List<Step> getOrderedSteps(final ScheduleActivity act) {
        return getOrderedSteps(act.getId());
    }
    
    /**
     * Returns an ordered list of steps for an activity.
     * @param activityId the id of the activity.
     * @return an ordered list of steps.
     */
    public List<Step> getOrderedSteps(final int activityId) {
        List<Step> entries = new ArrayList<Step>();
        
        try {
            final QueryBuilder<Step, Integer> query = getDao().queryBuilder();
            
            final SelectArg idClause = new SelectArg();
            query.where().eq(Step.ACTIVITY_ID_FIELD, idClause);
            query.orderBy(Step.ORDER_FIELD, true);
            
            final PreparedQuery<Step> preparedQuery = query.prepare();
            
            idClause.setValue(activityId);
            
            entries = getDao().query(preparedQuery);
            
        } catch (SQLException e) {
        	throw new RuntimeException(LOG_NAME, e);
        }
        
        return entries;
    }
}